package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.AssistCatchData;
import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.domain.CaiNaioInventory;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;

/**
 * @author Administrator url-->
 *         http://order.shop.jd.com/order/sSopUp_newYiShipList.action 1.
 * 
 * 
 */

@Service
public class SupplierCAINIAODataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {

	private static Logger log = LoggerFactory
			.getLogger(SupplierCAINIAODataCatchServiceImpl.class);

	private static Map<String, List<String>> mapcheck = new HashMap<String, List<String>>();

	@Override
	public boolean init(AssistCatchData assistCatchData) {
		super.init(assistCatchData);

		List<String> list = new ArrayList<String>();
		list.add("美的塔扇FZ10-15BRW");
		mapcheck.put(this.getAssistCatchData().getStartMess().getPlatformUser().getUsername(), list);

		return true;
	}

	//
	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {
		int loginCount = 0;
		// 开始登陆

		// 开始登陆 最多登陆三次（验证码错误情况）
		// 登陆返回信息
		boolean loginFlag =false;
		while (loginCount < 2) {

			loginCount++;

			this.getWebDriver().get(baseUrl);

			WebElement iframe = this.getWebDriver().findElement("css",
					"body > div.content > div.wrap-login > iframe");

			this.getWebDriver().switchToframe(iframe);

			this.getWebDriver().sendKeys("id", "TPL_username_1", username);
			this.getWebDriver().sendKeys("id", "TPL_password_1", password);

			WaitUtil.waitTimeSeconds(60);

			this.getWebDriver().click("id", "J_SubmitStatic");
			loginFlag = this.getWebDriver().isLogin(
					"http://work.cainiao.com/");
			
			if(loginFlag){
				return loginFlag;
			}

		}

		return loginFlag;

	}

	public void verifycode() throws Exception {
	}

	@Override
	public String catchSupplierName() throws BusinessException {
		// 店铺信息url TODO
		return null;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		return bcc;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {

		/*
		 * EmailMessage em =
		 * AlipayDispatcher.emailMessage.get(this.getStartMess(
		 * ).getPlatformUser().getUsername());
		 * 
		 * if(!CommonUtils.isEmpty(em)){ AlipayAccount aa =
		 * em.getAlipayAccountMain(); if(!CommonUtils.isEmpty(aa) &&
		 * !CommonUtils
		 * .isEmpty(aa.getAlipayCheckException().getAvailableBalance()) &&
		 * !CommonUtils
		 * .isEmpty(aa.getAlipayCheckException().getDisableBalance())){
		 * List<TbSlSupplyPayment> payments = new
		 * ArrayList<TbSlSupplyPayment>(); if(!CommonUtils.isEmpty(payments)){
		 * 
		 * // 可用余额 TbSlSupplyPayment availablebalance = new TbSlSupplyPayment();
		 * availablebalance.setPlatformAccountId(this.getStartMess()
		 * .getPlatformUser().getId());
		 * availablebalance.setSettlementId(aa.getUsername());
		 * availablebalance.setCreateDate(TimeUtils.getCurDate());
		 * 
		 * availablebalance.setSettlementState(TbSlSupplyPayment.AVAILABLEBALANCE
		 * ); availablebalance.setAmount(aa.getAlipayCheckException().
		 * getAvailableBalance());
		 * 
		 * // 不可用余额 TbSlSupplyPayment disableBalance = new TbSlSupplyPayment();
		 * disableBalance.setPlatformAccountId(this.getStartMess()
		 * .getPlatformUser().getId());
		 * disableBalance.setSettlementId(aa.getUsername());
		 * disableBalance.setCreateDate(TimeUtils.getCurDate());
		 * 
		 * disableBalance.setSettlementState(TbSlSupplyPayment.UNAVAILABLEBALANCE
		 * );
		 * disableBalance.setAmount(aa.getAlipayCheckException().getDisableBalance
		 * ());
		 * 
		 * payments.add(availablebalance); payments.add(disableBalance);
		 * 
		 * this.getCata().setSettlement(payments); LogUtils.info(log,
		 * "getUnpayAccountData()-->执行完毕:");
		 * 
		 * 
		 * 
		 * 
		 * } } }
		 */

		return true;

	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {

		CaiNaioInventory ca = new CaiNaioInventory();
        ca.setUsername( this.getAssistCatchData().getStartMess().getPlatformUser().getUsername());
        
        
		List<TbSlSupplyInventory> list = new ArrayList<TbSlSupplyInventory>();

		TbSlSupplyInventory num = new TbSlSupplyInventory();
		TbSlSupplyInventory innum = new TbSlSupplyInventory();
		
		num.setPlatformAccountId( this.getAssistCatchData().getStartMess().getPlatformUser()
				.getId());
		innum.setPlatformAccountId( this.getAssistCatchData().getStartMess().getPlatformUser()
				.getId());
		
		
		initNum(ca);
		
		num.setItemId(ca.getInventoryMoneyInDetail());
		num.setItemKey("美的塔扇FZ10-15BRW");
		num.setStoreDate(TimeUtils.getCurDate());
		num.setTotalCost(ca.getInventoryMoneyIn().longValue());
		num.setItemStatus(TbSlSupplyInventory.IN);
		
		innum.setItemId(ca.getInventoryMoneyOnTheWayDetail());
		innum.setItemKey("美的塔扇FZ10-15BRW");
		innum.setStoreDate(TimeUtils.getCurDate());
		innum.setTotalCost(ca.getInventoryMoneyOnTheWay().longValue());
		innum.setItemStatus(TbSlSupplyInventory.IN);
		

		list.add(num);
		list.add(innum);

		 this.getAssistCatchData().getCata().setInstore(list);
		return true;
	}

	public void initNum(CaiNaioInventory caiNaioInventory) {
		String currentAccountUrl = "http://dip.work.cainiao.com/inventory/scItemQuery.htm";

		this.getWebDriver().get(currentAccountUrl);// 对账单

		//this.getWebDriver().click("id", "J_searchBtn");

		int page = 1;

		String pageStr = this.getWebDriver().getText("css",
				"#J_Paging > div.paging-total-page > span");

		int total = Integer.valueOf(pageStr);

		while (page <= total) {
			page++;
			WebElement div = this.getWebDriver().findElement("css",
					"#J_DataTable > div.grid-table-rows-ct");

			WebElement div1 = this.getWebDriver().findElement(div,
					WebDriverService.className, "grid-table-rows-ct-inner");

			List<WebElement> divs = this.getWebDriver().findElements(div1,
					WebDriverService.className, "grid-row-inner");

			if (!CommonUtils.isEmpty(divs)) {
				Iterator<WebElement> it = divs.iterator();
				while (it.hasNext()) {
					WebElement di = it.next();

					List<WebElement> divinners = this.getWebDriver()
							.findElements(di, WebDriverService.className,
									"grid-cell-inner");

					String itemId = divinners.get(1).getText();

					if (!CommonUtils.isEmpty(mapcheck.get( this.getAssistCatchData().getStartMess().getPlatformUser().getUsername()))
							&& mapcheck.get( this.getAssistCatchData().getStartMess().getPlatformUser().getUsername()).contains(itemId)) {

						int num = Integer.valueOf(divinners.get(2).getText());
						int innum = Integer.valueOf(divinners.get(6).getText());
					
						caiNaioInventory.setCainiaoNum(num);
						caiNaioInventory.setCainiaoNumOnTheWay(innum);
					}

				}
			}

		}
	}
	
	
	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}
	
	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
